package com.example.girls.fragments

import android.os.Bundle
import android.util.Log
import android.view.*
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.example.girls.R
import com.example.girls.adapter.GirlAdapter
import com.example.girls.viewModels.MyViewModel
import kotlinx.android.synthetic.main.fragment_girls.*
import kotlin.math.abs

/**
 * 图片画廊的第一个界面
 * implement recycleView
 * */
class GalleryFragment : Fragment() {
    // 引入viewModel,提供整个activity的数据
    val myViewModel by activityViewModels<MyViewModel>()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        setHasOptionsMenu(true) // 显示菜单栏
        return inflater.inflate(R.layout.fragment_girls, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        swipeRefreshLayout.isEnabled = false // 不愿意改变布局了，所以禁用了swipeRefresh的功能
        val girlAdapter = GirlAdapter(myViewModel) // 声明适配器为GirlAdapter
        // 通过观察网络变化并通知girlAdapter视图层面实时更新(主要还是footer视图的更新)
        myViewModel.dataStatusLiveData.observe(viewLifecycleOwner, Observer {
            girlAdapter.updateNetWorkStatus(it)
            girlAdapter.notifyItemChanged(girlAdapter.itemCount - 1)
        })
        // 对recycleView进行适配
        recycleView.apply {
            layoutManager =
                StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL) // 设置布局规则
            adapter = girlAdapter // 设置适配器
            // 对滑动操作进行监听 -> 触发footerView
            addOnScrollListener(object : RecyclerView.OnScrollListener() {
                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    super.onScrolled(recyclerView, dx, dy)
                    if (dy < 0) return
                    val layoutManager = layoutManager as StaggeredGridLayoutManager
                    val intArray = IntArray(2)
                    layoutManager.findLastVisibleItemPositions(intArray)
                    // 取回最后一项进行数据追加
                    if (intArray[0] == girlAdapter.itemCount - 1) {
                        myViewModel.fetchData()
                    }
                }
            })
        }
        // 列表数据进行观察 -> 当数据发生变化时将数据上交给girlAdapter 并且此时数据已将加载成功 swipeRefreshLayout.isRefreshing = false
        myViewModel.photoListLiveData.observe(viewLifecycleOwner, Observer {
            // 当第一次加载的时候视图会下移，所以设置flag进行区分标识是否回到顶部
            if (myViewModel.needScrollToTop) {
                recycleView.scrollToPosition(0)
                myViewModel.needScrollToTop = false
            }
            girlAdapter.submitList(it)
            swipeRefreshLayout.isRefreshing = false
        })
        // 由于需要从另一个界面返回，将另一个正在浏览的图片位置取回到当前位置   如果超过6个距离差就滚动
        if (abs(myViewModel.currentPosition - myViewModel.perCurrentPosition) > 6) {
            recycleView.smoothScrollToPosition(myViewModel.currentPosition)
        }
    }

    // 一些menu的设置
    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        super.onCreateOptionsMenu(menu, inflater)
        inflater.inflate(R.menu.menu, menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.backToTop -> {
                recycleView.smoothScrollToPosition(0)
            }
            R.id.refresh -> {
                myViewModel.resetQuery()
                swipeRefreshLayout.isRefreshing = true
            }
        }
        return super.onOptionsItemSelected(item)
    }
}